package com.ant.storage.utils;

import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;

/**
 * 图片压缩上传工具类
 * @author hzd
 * @version 1.0
 * @date 2022/12/2 15:34
 */
public class ImageUtil {
    /**
     * 压缩图片至指定大小
     * @param sourceBytes   源
     * @param targetFileSize    目标
     * @param quality   压缩比例0-1最好小于0.9
     * @return
     * @throws Exception
     */
    public static byte[] compressImageCircle(byte[] sourceBytes, long targetFileSize, double quality) throws Exception{
        long sourceFileSize = sourceBytes.length;
        // 判断大小
        if (sourceFileSize <= targetFileSize * 1024) {
            return sourceBytes;
        }
        // 计算宽高
        BufferedImage bim = ImageIO.read(new ByteArrayInputStream(sourceBytes));
        int sourceWidth = bim.getWidth();
        int sourceHeight = bim.getHeight();
        int targetWidth = new BigDecimal(sourceWidth).multiply(new BigDecimal(quality)).intValue();
        int targetHeight = new BigDecimal(sourceHeight).multiply(new BigDecimal(quality)).intValue();

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        Thumbnails.of(new ByteArrayInputStream(sourceBytes)).size(targetWidth, targetHeight).outputQuality(quality).toOutputStream(byteArrayOutputStream);
        return compressImageCircle(byteArrayOutputStream.toByteArray(), targetFileSize, quality);

    }

    /**
     *  保存文件到文件夹
     * @param bytes
     * @param filePath  文件保存路径
     * @param fileName  保存文件的名字
     */
    //将Byte数组转换成文件
    public static String getFileByBytes(byte[] bytes, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            // 判断文件目录是否存在
            if (!dir.exists() && !dir.isDirectory()) {
               dir.mkdir();
            }
           // file = new File(filePath + "\\" + fileName);
            file = new File(filePath + fileName);
            System.out.println(file);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
            //System.out.println("图片路径:"+file+"图片名称:"+fileName);
            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
